<template>
  <div class="my-mooc-auth">
    <!-- 左侧人物插画 -->
    <div class="auth-left">
      <div class="illustration">
        <!-- 人物插画 -->
        <div class="person-illustration">
          <div class="person">
            <div class="person-head"></div>
            <div class="person-body"></div>
            <div class="person-arm-left"></div>
            <div class="person-arm-right"></div>
            <div class="person-leg-left"></div>
            <div class="person-leg-right"></div>
          </div>
          <div class="success-gesture">
            <div class="fist"></div>
          </div>
          <div class="book"></div>
          <div class="geometric-shapes">
            <div class="circle-blue"></div>
            <div class="circle-green"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧登录表单 -->
    <div class="auth-right">
      <div class="auth-form-container">
        <!-- Logo和欢迎信息 -->
        <div class="auth-header">
          <div class="logo">
            <span class="my">启</span>
            <span class="mooc">航</span>
          </div>
          <div class="logo-subtitle">公益编程学习平台</div>
          
          <h1 class="welcome-title">欢迎 👋</h1>
          <p class="welcome-subtitle">使用以下登录或创建启航账户</p>
        </div>

        <!-- 登录表单 -->
        <form @submit.prevent="handleLogin" class="login-form">
          <!-- 邮箱/用户名输入 -->
          <div class="form-group">
            <input 
              v-model="loginForm.username"
              type="text" 
              placeholder="用户名或邮箱"
              class="form-input"
              required
            >
          </div>

          <!-- 密码输入 -->
          <div class="form-group">
            <input 
              v-model="loginForm.password"
              type="password" 
              placeholder="密码"
              class="form-input"
              required
            >
          </div>

          <!-- 记住我 -->
          <div class="form-group checkbox-group">
            <label class="checkbox-label">
              <input type="checkbox" v-model="rememberMe" class="checkbox">
              记住我
            </label>
          </div>

          <!-- 验证码 -->
          <div class="form-group captcha-group">
            <input 
              v-model="loginForm.captchaCode"
              type="text" 
              placeholder="验证码"
              class="form-input captcha-input"
              required
            >
            <img 
              :src="captchaImage" 
              alt="验证码" 
              @click="refreshCaptcha" 
              class="captcha-image" 
              title="点击刷新验证码" 
            />
          </div>

          <!-- 下一步按钮 -->
          <button 
            type="submit" 
            class="next-btn" 
            :disabled="loading"
          >
            <span v-if="!loading">下一步</span>
            <span v-else>登录中...</span>
          </button>

          <!-- 底部链接 -->
          <div class="auth-footer">
            <p class="help-text">
              需要帮助？
              <a href="#" class="help-link">联系我们！</a>
            </p>
            
            <div class="footer-links">
              <a href="#" class="footer-link">使用条款</a>
              <a href="#" class="footer-link">隐私政策</a>
              <a href="#" class="footer-link">Accessibility</a>
            </div>

            <!-- 语言选择 -->
            <div class="language-selector">
              <span class="current-lang">ZH</span>
              <span class="lang-option">中文(简体)</span>
              <svg class="dropdown-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <polyline points="6,9 12,15 18,9"></polyline>
              </svg>
            </div>
          </div>

          <!-- 注册链接 -->
          <div class="register-prompt">
            还没有账户？
            <router-link to="/register" class="register-link">立即注册</router-link>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import api from '@/api/http'

const router = useRouter()
const authStore = useAuthStore()

const loginForm = ref({
  username: '',
  password: '',
  captchaKey: '',
  captchaCode: ''
})

const loading = ref(false)
const rememberMe = ref(false)
const captchaImage = ref('')

// 获取验证码key和图片
const getCaptcha = async () => {
  try {
    console.log('开始获取验证码key');
    const keyResponse = await api.get('/v1/captcha/key')
    console.log('验证码key响应:', keyResponse);
    loginForm.value.captchaKey = keyResponse.key
    
    console.log('开始获取验证码图片，key:', loginForm.value.captchaKey);
    const imageResponse = await api.get(`/v1/captcha/image/${loginForm.value.captchaKey}`)
    console.log('验证码图片响应:', imageResponse);
    captchaImage.value = imageResponse.image
  } catch (error) {
    console.error('获取验证码失败:', error);
    ElMessage.error('获取验证码失败')
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  if (loginForm.value.captchaCode && loginForm.value.captchaCode.trim() !== '') {
    if (confirm('您已经输入了验证码，刷新验证码将清除当前输入，确定要刷新吗？')) {
      getCaptcha()
      loginForm.value.captchaCode = ''
    }
  } else {
    getCaptcha()
  }
}

// 页面加载时获取验证码
onMounted(() => {
  getCaptcha()
})

const handleLogin = async () => {
  if (!loginForm.value.username || !loginForm.value.password || !loginForm.value.captchaCode) {
    ElMessage.error('请填写完整信息')
    return
  }

  loading.value = true
  try {
    // 验证验证码
    console.log('开始验证验证码，key:', loginForm.value.captchaKey, 'code:', loginForm.value.captchaCode);
    try {
      const captchaValidation = await api.post('/v1/captcha/validate', null, {
        params: { key: loginForm.value.captchaKey, code: loginForm.value.captchaCode }
      })
      console.log('验证码验证响应:', captchaValidation);
      
      if (!captchaValidation.valid) {
        ElMessage.error(captchaValidation.message || '验证码错误')
        refreshCaptcha()
        return
      }
    } catch (error: any) {
      console.error('验证码验证失败:', error);
      if (error.response && error.response.status === 400) {
        ElMessage.error('验证码验证失败，请检查验证码是否正确或已过期')
      } else {
        ElMessage.error(error.message || '验证码验证失败')
      }
      return
    }
    
    const success = await authStore.login(loginForm.value)
    if (success) {
      ElMessage.success('登录成功')
      await new Promise(resolve => setTimeout(resolve, 100))
      router.replace('/courses')
    } else {
      ElMessage.error('登录失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败')
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 完全按照My MOOC登录页面样式 */
.my-mooc-auth {
  min-height: 100vh;
  display: flex;
  background: #f0f4f8;
}

/* 左侧插画区域 */
.auth-left {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.illustration {
  position: relative;
  width: 400px;
  height: 400px;
}

/* 人物插画 */
.person-illustration {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.person {
  position: relative;
  z-index: 3;
}

.person-head {
  width: 60px;
  height: 60px;
  background: #f4c2a1;
  border-radius: 50%;
  position: relative;
  margin: 0 auto 5px;
}

.person-body {
  width: 80px;
  height: 100px;
  background: #4a90e2;
  border-radius: 40px 40px 20px 20px;
  margin: 0 auto;
  position: relative;
}

.person-arm-left {
  position: absolute;
  top: 80px;
  left: -15px;
  width: 20px;
  height: 60px;
  background: #4a90e2;
  border-radius: 10px;
  transform: rotate(-30deg);
}

.person-arm-right {
  position: absolute;
  top: 70px;
  right: -25px;
  width: 20px;
  height: 70px;
  background: #4a90e2;
  border-radius: 10px;
  transform: rotate(45deg);
}

.person-leg-left {
  position: absolute;
  bottom: -40px;
  left: 15px;
  width: 20px;
  height: 50px;
  background: #333;
  border-radius: 10px;
}

.person-leg-right {
  position: absolute;
  bottom: -40px;
  right: 15px;
  width: 20px;
  height: 50px;
  background: #333;
  border-radius: 10px;
}

/* 成功手势 */
.success-gesture {
  position: absolute;
  top: 40px;
  right: -30px;
  z-index: 4;
}

.fist {
  width: 30px;
  height: 30px;
  background: #f4c2a1;
  border-radius: 50%;
  position: relative;
}

.fist::after {
  content: '✊';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
}

/* 书本 */
.book {
  position: absolute;
  bottom: 50px;
  right: 30px;
  width: 40px;
  height: 30px;
  background: #ff6b6b;
  border-radius: 4px;
  z-index: 2;
}

.book::after {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  right: 2px;
  bottom: 2px;
  background: #fff;
  border-radius: 2px;
}

/* 几何图形 */
.geometric-shapes {
  position: absolute;
  width: 100%;
  height: 100%;
}

.circle-blue {
  position: absolute;
  top: 20px;
  left: 50px;
  width: 120px;
  height: 120px;
  background: rgba(74, 144, 226, 0.8);
  border-radius: 50%;
  z-index: 1;
}

.circle-green {
  position: absolute;
  bottom: 30px;
  left: 20px;
  width: 80px;
  height: 80px;
  background: rgba(82, 196, 26, 0.6);
  border-radius: 50%;
  z-index: 1;
}

/* 右侧表单区域 */
.auth-right {
  flex: 0 0 500px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.auth-form-container {
  width: 100%;
  max-width: 400px;
}

/* 认证头部 */
.auth-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  display: flex;
  justify-content: center;
  align-items: baseline;
  font-size: 32px;
  font-weight: 300;
  margin-bottom: 8px;
}

.my {
  color: #4A90E2;
  margin-right: 4px;
}

.mooc {
  color: #4A90E2;
  font-weight: 600;
}

.logo-subtitle {
  font-size: 12px;
  color: #999;
  font-style: italic;
  margin-bottom: 32px;
}

.welcome-title {
  font-size: 24px;
  font-weight: 400;
  color: #333;
  margin-bottom: 8px;
}

.welcome-subtitle {
  font-size: 14px;
  color: #666;
  margin-bottom: 0;
}

/* 登录表单 */
.login-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  height: 48px;
  padding: 0 16px;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  background: white;
  transition: all 0.2s;
}

.form-input:focus {
  outline: none;
  border-color: #4A90E2;
  box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
}

.form-input::placeholder {
  color: #999;
}

/* 复选框组 */
.checkbox-group {
  display: flex;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.checkbox {
  width: 16px;
  height: 16px;
  accent-color: #4A90E2;
}

/* 验证码组 */
.captcha-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 48px;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  cursor: pointer;
  object-fit: cover;
  transition: border-color 0.2s;
}

.captcha-image:hover {
  border-color: #4A90E2;
}

/* 下一步按钮 */
.next-btn {
  width: 100%;
  height: 48px;
  background: #5a67d8;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 32px;
}

.next-btn:hover:not(:disabled) {
  background: #4c51bf;
  transform: translateY(-1px);
}

.next-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 认证底部 */
.auth-footer {
  text-align: center;
  margin-bottom: 32px;
}

.help-text {
  font-size: 12px;
  color: #666;
  margin-bottom: 16px;
}

.help-link {
  color: #4A90E2;
  text-decoration: none;
}

.help-link:hover {
  text-decoration: underline;
}

.footer-links {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 16px;
}

.footer-link {
  font-size: 12px;
  color: #666;
  text-decoration: none;
}

.footer-link:hover {
  color: #4A90E2;
}

/* 语言选择器 */
.language-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 12px;
  color: #4A90E2;
  cursor: pointer;
}

.current-lang {
  font-weight: 600;
}

.dropdown-icon {
  color: #999;
}

/* 注册提示 */
.register-prompt {
  text-align: center;
  font-size: 14px;
  color: #666;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

.register-link {
  color: #4A90E2;
  text-decoration: none;
  font-weight: 500;
}

.register-link:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-mooc-auth {
    flex-direction: column;
  }
  
  .auth-left {
    min-height: 40vh;
    padding: 30px;
  }
  
  .illustration {
    width: 300px;
    height: 300px;
  }
  
  .auth-right {
    flex: none;
    padding: 30px 20px;
  }
  
  .auth-form-container {
    max-width: none;
  }
}

@media (max-width: 480px) {
  .auth-left {
    min-height: 35vh;
    padding: 20px;
  }
  
  .illustration {
    width: 250px;
    height: 250px;
  }
  
  .welcome-title {
    font-size: 20px;
  }
  
  .captcha-group {
    flex-direction: column;
    gap: 12px;
  }
  
  .captcha-image {
    width: 100%;
    max-width: 200px;
  }
}
</style>